﻿using System;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using Abp.Configuration.Startup;
using Abp.MultiTenancy;
using Abp.Runtime;
using Abp.Runtime.Security;
using Abp.Runtime.Session;

namespace Hicap.AuthorizationServer.Core.Common
{
    public partial class HicapSession : AbpSessionBase, IAbpSession
    {
        private const int DefaultTenantId = 1;
        protected IPrincipalAccessor PrincipalAccessor { get; }

        public override long? UserId
        {
            get
            {
                ClaimsPrincipal principal = this.PrincipalAccessor.Principal;

                Claim claim = principal != null
                    ? principal.Claims.FirstOrDefault(c => c.Type == AbpClaimTypes.UserId)
                    : (Claim)null;

                if (!string.IsNullOrEmpty(claim?.Value))
                    return new int?(Convert.ToInt32(claim.Value));

                return new int?();
            }
        }

        public override int? TenantId => DefaultTenantId;

        public override long? ImpersonatorUserId => null;

        public override int? ImpersonatorTenantId => DefaultTenantId;

        /// <summary>
        /// Constructor.
        /// </summary>
        public HicapSession(IPrincipalAccessor principalAccessor, IMultiTenancyConfig multiTenancy,
            IAmbientScopeProvider<SessionOverride> sessionOverrideScopeProvider) : base(multiTenancy,
            sessionOverrideScopeProvider)
        {
            PrincipalAccessor = principalAccessor;
        }
    }
}